//
//  GroupViewController.m
//  SuiRan_Demo
//
//  Created by lanou3g on 15-4-27.
//  Copyright (c) 2015年 fzg. All rights reserved.
//

#import "GroupViewController.h"

#import "GroupCell.h"
#import "GroupCell2.h"
#import "GroupHotList.h"
#import "GroupDetailList.h"
#import "ViewController.h"
#import "RESideMenu.h"


#import "GroupDetailTableViewController.h"



@interface GroupViewController () <NSURLConnectionDataDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableData *allData;

@property (nonatomic, retain) NSMutableArray *allHotDataArray;
@property (nonatomic, retain) NSMutableArray *allNewDataArray;

@property (nonatomic, retain) UISegmentedControl *segmentedControl;
@property (nonatomic, assign) NSInteger flag;
@property (nonatomic, assign) CGFloat start;

//@property (nonatomic, copy) NSMutableArray *mutableHotArray;
//@property (nonatomic, copy) NSMutableArray *mutableNewArray;
@end

@implementation GroupViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // 设置左navigationbarButton
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)] autorelease];
    
    // 设置右navigationbarButton
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"RightMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(presentRightMenuViewController:)] autorelease];
    
    
    
    
    self.start = 0;
    self.flag = 1;
    [self loadViews];
    
    [self loadData];
    
    [self refresh];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"GroupCell" bundle:nil] forCellReuseIdentifier:@"Group"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GroupCell2" bundle:nil] forCellReuseIdentifier:@"Group2"];
    
 
    
    [self.segmentedControl addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
}


- (void)refresh
{
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.tableView.footer.automaticallyRefresh = NO;
}

- (void)loadMoreData
{
    self.start += 10;
    NSLog(@"%f", _start);
    
    //
    NSURL *url = [NSURL URLWithString:kGroupList];
    NSData *paramData1 = [GroupList_Hot(_start) dataUsingEncoding:NSUTF8StringEncoding];
    NSData *paramData2 = [GroupList_New(_start) dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //    NSLog(@"~~~~~~~~~~~~~%ld", request.retainCount);
    [request setHTTPMethod:@"POST"];
    
    if (self.flag == 1) {
        [request setHTTPBody:paramData1];
    } else if (self.flag == 2){
        [request setHTTPBody:paramData2];
    }
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    //    NSLog(@"！！！！！！ %ld", request.retainCount);

//    NSLog(@"%@", _allDataArray);
    [self.tableView reloadData];
    
    [self.tableView.footer endRefreshing];
}

- (void)loadNewData
{
    self.allHotDataArray = [NSMutableArray array];
    self.allNewDataArray = [NSMutableArray array];
    
    NSURL *url = [NSURL URLWithString:kGroupList];
    NSData *paramData1 = [GroupList_Hot(_start) dataUsingEncoding:NSUTF8StringEncoding];
    NSData *paramData2 = [GroupList_New(_start) dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //    NSLog(@"~~~~~~~~~~~~~%ld", request.retainCount);
    [request setHTTPMethod:@"POST"];
    
    if (self.flag == 1) {
        [request setHTTPBody:paramData1];
    } else if (self.flag == 2){
        [request setHTTPBody:paramData2];
    }
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    //    NSLog(@"！！！！！！ %ld", request.retainCount);
    
    //    NSLog(@"%@", _allDataArray);
    [self.tableView reloadData];
    
    [self.tableView.header endRefreshing];
}


#pragma mark - segmentedControl的方法
- (void)segmentedControlAction:(UISegmentedControl *)sender
{
    switch (sender.selectedSegmentIndex) {
        case 0: {
            self.flag = 1;
            self.start = 0;
            [self loadData];
            break;
        }
        case 1: {
            self.flag = 2;
            self.start = 0;
            [self loadData];
            break;
        }
            
        default:
            break;
    }
}

- (void)loadViews{
    
    // 添加SegmentedControl
    self.segmentedControl = [[[UISegmentedControl alloc] initWithItems:@[@"最热", @"最新"]] autorelease];
    self.segmentedControl.tintColor = [UIColor whiteColor];
//    self.segmentedControl.alpha = 1.0;
    
    _segmentedControl.frame = CGRectMake(0, 64, CGRectGetWidth([UIScreen mainScreen].bounds), 50);
    
    // 默认选中项
    _segmentedControl.selectedSegmentIndex = 0;
    [self.view addSubview:_segmentedControl];
    
    // 添加tableView
    self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segmentedControl.frame), CGRectGetWidth([UIScreen mainScreen].bounds), self.view.frame.size.height - _segmentedControl.frame.size.height - 64) style:UITableViewStylePlain] autorelease];
    [self.view addSubview:_tableView];
    

}



- (void)loadData
{
//    self.mutableHotArray = [NSMutableArray array];
//    self.mutableNewArray = [NSMutableArray array];
    // 解析数据
    self.allHotDataArray = [NSMutableArray array];
    self.allNewDataArray = [NSMutableArray array];
    
    
    NSURL *url = [NSURL URLWithString:kGroupList];
    NSData *paramData1 = [GroupList_Hot(_start) dataUsingEncoding:NSUTF8StringEncoding];
    NSData *paramData2 = [GroupList_New(_start) dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    NSLog(@"~~~~~~~~~~~~~%ld", request.retainCount);
    [request setHTTPMethod:@"POST"];
    
    if (self.flag == 1) {
        [request setHTTPBody:paramData1];
    } else if (self.flag == 2){
        [request setHTTPBody:paramData2];
    }
    
    [NSURLConnection connectionWithRequest:request delegate:self];
//    NSLog(@"！！！！！！ %ld", request.retainCount);
    
    
}



#pragma mark - NSURLConnectionDataDelegate
#pragma mark 开始接受请求结果
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.allData = [NSMutableData data];
}

#pragma mark 接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_allData appendData:data];
}

#pragma mark 数据接收完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    NSLog(@"yuyugd %ld", _flag);
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_allData options:NSJSONReadingAllowFragments error:nil];
//    if (_flag == 1) {
//        self.mutableHotArray = dict[@"data"][@"list"];
//    } else if (_flag == 2) {
//        self.mutableNewArray = dict[@"data"][@"list"];
//    }
    
//    NSLog(@"~~~hot!!!!!!%@", self.mutableHotArray);
//    NSLog(@"~~~new!!!!!!%@", self.mutableNewArray);

    
    for (NSDictionary *item in dict[@"data"][@"list"]) {
        
        GroupHotList * group = [GroupHotList new];
        [group setValuesForKeysWithDictionary:item];
        
        if (_flag == 1) {
            [self.allHotDataArray addObject:group];
        } else if (_flag == 2) {
            [self.allNewDataArray addObject:group];
        }
        [group release];
    }
    
//    NSLog(@"%@", _allDataArray);
    
    [self.tableView reloadData];
}

#pragma mark 发生错误，执行此方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
}






#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_flag == 1) {
        return _allHotDataArray.count;
    } else {
        return _allNewDataArray.count;
    }
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"~~~~~~~~~%ld", _flag);
    GroupHotList *group = [[GroupHotList new] autorelease];
    if (_flag == 1) {
        group = _allHotDataArray[indexPath.row];
    } else if (_flag == 2) {
        group = _allNewDataArray[indexPath.row];
    }
    
//    NSMutableDictionary *dict = (NSMutableDictionary *)group.counterList;
//    NSLog(@"!!!%@", dict[@"comment"]);


    if (![group.coverimg isEqualToString:@""]) {
        
        GroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Group" forIndexPath:indexPath];
        cell.titleLabel.text = group.title;
        cell.introduceLabel.text = group.content;
        cell.timeLabel.text = group.addtime_f;
        
        NSMutableDictionary *dict = (NSMutableDictionary *)group.counterList;
        
        
        // 使用SDwebImage下载网络图片
//        [cell.nameImageView sd_setImageWithURL:[NSURL URLWithString:group.coverimg]];
        [cell.nameImageView sd_setImageWithURL:[NSURL URLWithString:group.coverimg] placeholderImage:[UIImage imageNamed:@"wait"]];
        
        
//        if (group.imageData == nil) {
//            //    if ([group.imageData isEqual:[NSNull null]]) {
//            [group.imageData addObserver:self forKeyPath:@"imageData" options:NSKeyValueObservingOptionNew context:indexPath];
//            
//        } else {
//            cell.nameImageView.image = group.imageData;
//            //            NSLog(@"%@", group.imageData);
//        }
        
        cell.commentCountLabel.text = [NSString stringWithFormat:@"%@", dict[@"comment"]];

        return cell;
        
    } else {   
        GroupCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"Group2" forIndexPath:indexPath];
        cell.nameLabel.text = group.title;
        cell.introduceLabel.text = group.content;
        cell.timeLabel.text = group.addtime_f;
        NSMutableDictionary *dict = (NSMutableDictionary *)group.counterList;
        
        
        
        cell.commentCountLabel.text = [NSString stringWithFormat:@"%@", dict[@"comment"]];
        
        
        
        return cell;
    }
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GroupHotList *group = [[GroupHotList new] autorelease];
    if (_flag == 1) {
        group = _allHotDataArray[indexPath.row];
    } else if (_flag == 2) {
        group = _allNewDataArray[indexPath.row];
    }

    if ([group.coverimg isEqualToString:@""]) {
        return 160;
    } else {
        return 190;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"!!!!!~~~~!!!!!%ld", _flag);
   

    GroupHotList *group = [[GroupHotList new] autorelease];
    if (_flag == 1) {
        group = _allHotDataArray[indexPath.row];
    } else if (_flag == 2) {
        group = _allNewDataArray[indexPath.row];

    }
    
    /*
//    NSString *str = [NSString string];
//    
//    if (_flag == 1) {
//
//        str = _mutableHotArray[indexPath.row][@"userinfo"][@"uname"];
//        
//    } else if (_flag == 2) {
//        str = _mutableNewArray[indexPath.row][@"userinfo"][@"uname"];
//    }
     */
    
//    GroupDetailViewController *groupDetailVC = [[GroupDetailViewController new] autorelease];
//    
//
//    groupDetailVC.groupHot = group;
//    
//    
//    
//    [self.navigationController showViewController:groupDetailVC sender:nil];
    
    GroupDetailTableViewController *groupDetailTVC = [[GroupDetailTableViewController new] autorelease];
    
    groupDetailTVC.groupHot = group;
    
    [self.navigationController showViewController:groupDetailTVC sender:nil];
    
}


//#pragma mark - 观察者发现后执行的方法
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
//{
//    NSIndexPath *indexPath = (NSIndexPath *) context;
//    UIImage *newImage = change[@"new"];
//    
//    NSLog(@"%@", newImage);
//    
//    GroupCell *cell = (GroupCell *)[self.tableView cellForRowAtIndexPath:indexPath];
//    cell.nameImageView.image = newImage;
//    
//    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//    [object removeObserver:self forKeyPath:keyPath context:context];
//}

- (void)dealloc
{
    [_allData release];
    [_allHotDataArray release];
    [_allNewDataArray release];
    [_segmentedControl release];
    [_tableView release];
    
//    [_mutableHotArray release];
//    [_mutableNewArray release];
    
    [super dealloc];
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
